/*
 * @Author: your name
 * @Date: 2021-09-01 16:37:25
 * @LastEditTime: 2021-11-04 14:31:13
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \web-maps\src\util\mdfs\BinaryReader.ts
 */

// import BinaryReaderError from "./BinaryReaderError";

// const validationLength = () => {
//   return (target, key, descriptor) => {};
// };

export default class BinaryReader {
  private dataView: DataView;

  private offset = 0;

  private byteLength: number;

  constructor(dataView: DataView) {
    this.dataView = dataView;
    this.byteLength = dataView.byteLength;
  }

  get Offset() {
    return this.offset;
  }

  get ByteLength() {
    return this.byteLength;
  }

  // @validationLength()
  ReadChars(count: number) {
    const chars: Array<string> = [];
    for (let i = 0; i < count; i++) {
      chars.push(String.fromCharCode(this.dataView.getInt8(this.offset)));
      this.offset += 1;
    }
    return chars;
  }

  ReadInt16(littleEndian = true) {
    const val = Number.parseInt(
      this.dataView.getInt16(this.offset, littleEndian).toString()
    );
    this.offset += 2;
    return val;
  }

  ReadUInt16(littleEndian = true) {
    const val = Number.parseInt(
      this.dataView.getUint16(this.offset, littleEndian).toString()
    );
    this.offset += 2;
    return val;
  }

  ReadInt32(littleEndian = true) {
    //处理经度问题
    const val = Number.parseInt(
      this.dataView.getInt32(this.offset, littleEndian).toString()
    );
    this.offset += 4;
    return val;
  }

  ReadFloat32(figures = 6, littleEndian = true) {
    const val = Number.parseFloat(
      this.dataView.getFloat32(this.offset, littleEndian).toFixed(figures)
    );
    // const val = this.dataView.getFloat32(this.offset,littleEndian);
    this.offset += 4;
    return val;
  }

  ReadFloat64(figures = 6, littleEndian = true) {
    const val = Number.parseFloat(
      this.dataView.getFloat64(this.offset, littleEndian).toFixed(figures)
    );
    // const val = this.dataView.getFloat64(this.offset,littleEndian);
    this.offset += 8;
    return val;
  }

  ReadBytes(count: number) {
    const bytes = new Uint8Array(
      this.dataView.buffer.slice(this.offset, this.offset + count)
    );
    this.offset += +count;
    return bytes;
  }

  replaceEnd(str: Array<string>) {
    return str.join("").replace(/\0/g, "").trim();
  }
}
